import { ref } from "vue";

let g_iWndIndex = 0; // 表示当前窗口
let g_iSearchTimes = 0;

class HkVideoService {
  constructor() {
    this.log = ref("");
    this.szDeviceIdentify = ref(null);
    this.channels = ref([]);
    this.selectedChannel = ref(null);
    this.divId = ref("divPlugin");
    this.playFastClickCount = 0;
    this.searchResults = ref([]);
    this.downloadID = ref(-1);
    this.downloadProcess = ref(0);
  }

  showInfo(content) {
    const now = new Date();

    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    const hours = String(now.getHours()).padStart(2, "0");
    const minutes = String(now.getMinutes()).padStart(2, "0");
    const seconds = String(now.getSeconds()).padStart(2, "0");

    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    this.log.value += `[${formattedTime}] - ${content}\n`;
    console.log(`[${formattedTime}] - ${content}`);
  }

  initPlugin(divId) {
    WebVideoCtrl.I_InitPlugin({
      bWndFull: true,
      iWndowType: 1,
      bDebugMode: true,
      cbInitPluginComplete: () => {
        WebVideoCtrl.I_InsertOBJECTPlugin(divId).then(
          () => {
            this.showInfo("插件初始化成功！");

            WebVideoCtrl.I_CheckPluginVersion().then((bFlag) => {
              if (bFlag) {
                alert(
                  "检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！"
                );
              }
            });
          },
          () => {
            alert(
              "插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！"
            );
          }
        );
      },
    });
  }

  async destroyPlugin() {
    try {
      await WebVideoCtrl.I_DestroyPlugin();
      this.showInfo(`销毁插件成功！`);
    } catch (error) {
      this.showInfo(`销毁插件失败！原因：${error}`);
    }
  }

  // login(loginConfig) {
  //   WebVideoCtrl.I_Login(
  //     loginConfig.ip,
  //     1,
  //     loginConfig.port,
  //     loginConfig.username,
  //     loginConfig.password,
  //     {
  //       timeout: 3000,
  //       success: (xmlDoc) => {
  //         this.szDeviceIdentify.value = loginConfig.ip + "_" + loginConfig.port;
  //         console.log("登录成功");
  //         this.showInfo(`登录成功！设备标识：${this.szDeviceIdentify.value}`);

  //         // setTimeout(() => {
  //         //   this.getChannelList();
  //         // }, 500);
  //       },
  //       error: (error) => {
  //         console.log("登录失败，原因：", error);
  //       },
  //     }
  //   );
  // }

  async login(loginConfig) {
    try {
      await WebVideoCtrl.I_Login(
        loginConfig.ip,
        1,
        loginConfig.port,
        loginConfig.username,
        loginConfig.password,
        { timeout: 3000 }
      );

      this.szDeviceIdentify.value = loginConfig.ip + "_" + loginConfig.port;
      this.showInfo(`登录成功！设备标识：${this.szDeviceIdentify.value}`);
    } catch (error) {
      console.log("登录失败，原因：", error);
    }
  }

  async logout() {
    if (null == this.szDeviceIdentify.value) {
      return;
    }

    try {
      await WebVideoCtrl.I_Logout(this.szDeviceIdentify.value);
      this.showInfo(`登出成功！设备标识：${this.szDeviceIdentify.value}`);
      this.szDeviceIdentify.value = null;
    } catch (error) {
      console.log("登出失败！原因：", error);
    }
  }

  getChannelList() {
    if (null == this.szDeviceIdentify.value) {
      console.log("获取通道失败，请检查是否登录");
      return;
    }

    WebVideoCtrl.I_GetDigitalChannelInfo(this.szDeviceIdentify.value, {
      success: (xmlDoc) => {
        const channelNodes = xmlDoc.getElementsByTagName(
          "InputProxyChannelStatus"
        );

        const tempChannels = [];

        this.showInfo(`可用通道数：${channelNodes.length}`);

        for (let i = 0; i < channelNodes.length; i++) {
          const channelNode = channelNodes[i];
          const id = channelNode.getElementsByTagName("id")[0]?.textContent;
          const name =
            channelNode.getElementsByTagName("name")[0]?.textContent ||
            `IPCamera ${i < 9 ? "0" + (i + 1) : i + 1}`;
          const online =
            channelNode.getElementsByTagName("online")[0]?.textContent;

          if (online === "false") {
            continue;
          }

          tempChannels.push({ id, name });
        }

        this.channels.value = tempChannels;

        console.log("获取数字通道成功！");
      },
      error: (error) => {
        this.showInfo(`获取数字通道失败！原因：${error}`);
      },
    });
  }

  startPreview() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (null == this.szDeviceIdentify.value) {
      return;
    }

    const startPlayback = () => {
      WebVideoCtrl.I_StartRealPlay(this.szDeviceIdentify.value, {
        iStreamType: 1,
        iChannelID: 1,
        success: () => {
          this.showInfo("开始预览成功");
        },
        error: (error) => {
          this.showInfo(`开始预览失败，原因：${error}`);
        },
      });
    };

    if (oWndInfo != null) {
      WebVideoCtrl.I_Stop({
        success: function () {
          startPlayback();
        },
      });
    } else {
      startPlayback();
    }
  }

  stopPreview() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (oWndInfo != null) {
      WebVideoCtrl.I_Stop({
        success: () => {
          this.showInfo("停止预览成功");
        },
        error: (error) => {
          console.log("停止预览失败，原因：", error);
        },
      });
    }
  }

  startPlayback(channelID, szStartTime, szEndTime) {
    let oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
    var bChecked = true;

    if (null == this.szDeviceIdentify.value) {
      return;
    }

    const startTime = new Date(szStartTime);
    const endTime = new Date(szEndTime);

    if (startTime > endTime) {
      this.showInfo("开始时间大于结束时间，操作无效。");
      return;
    }

    const startPlayback = () => {
      if (bChecked) {
        // 启用转码回放
        var oTransCodeParam = {
          TransFrameRate: "14", // 0：全帧率，5：1，6：2，7：4，8：6，9：8，10：10，11：12，12：16，14：15，15：18，13：20，16：22
          TransResolution: "1", // 255：Auto，3：4CIF，2：QCIF，1：CIF
          TransBitrate: "19", // 2：32K，3：48K，4：64K，5：80K，6：96K，7：128K，8：160K，9：192K，10：224K，11：256K，12：320K，13：384K，14：448K，15：512K，16：640K，17：768K，18：896K，19：1024K，20：1280K，21：1536K，22：1792K，23：2048K，24：3072K，25：4096K，26：8192K
        };
        WebVideoCtrl.I_StartPlayback(this.szDeviceIdentify.value, {
          iRtspPort: 8000,
          iStreamType: 1,
          iChannelID: channelID,
          szStartTime: szStartTime,
          szEndTime: szEndTime,
          oTransCodeParam: oTransCodeParam,
          success: function () {
            console.log("开始回放成功");
          },
          error: function (error) {
            console.log("开始回放失败，原因：", error);
          },
        });
      } else {
        WebVideoCtrl.I_StartPlayback(szDeviceIdentify, {
          iRtspPort: 8000,
          iStreamType: 1,
          iChannelID: 1,
          szStartTime: szStartTime,
          szEndTime: szEndTime,
          success: function () {
            console.log("开始回放成功");
          },
          error: function (oError) {
            console.log("开始回放失败，原因：", error);
          },
        });
      }
    };
    if (oWndInfo != null) {
      // 已经在播放了，先停止
      WebVideoCtrl.I_Stop({
        success: function () {
          startPlayback();
        },
      });
    } else {
      startPlayback();
    }
  }

  stopPlayback() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (oWndInfo != null) {
      WebVideoCtrl.I_Stop({
        success: () => {
          this.showInfo("停止回放成功");
        },
        error: (error) => {
          this.showInfo(
            `停止回放失败！错误码：${error.errorCode},错误信息：${error.errorMsg}`
          );
        },
      });
    }
  }

  pause() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (oWndInfo != null) {
      WebVideoCtrl.I_Pause({
        success: () => {
          this.showInfo("暂停成功");
        },
        error: (error) => {
          this.showInfo(
            `暂停失败！错误码：${error.errorCode}，错误信息：${error.errorMsg}`
          );
        },
      });
    }
  }

  resume() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (oWndInfo != null) {
      WebVideoCtrl.I_Resume({
        success: () => {
          this.showInfo("恢复成功！");
        },
        error: (error) => {},
      });
    }
  }

  playFast() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (oWndInfo != null) {
      WebVideoCtrl.I_PlayFast({
        success: () => {
          this.playFastClickCount += 1;
        },
        error: (error) => {
          this.showInfo(
            `快进失败！错误码：${error.errorCode}，错误信息：${error.errorMsg}`
          );
        },
      });
    }
  }

  playSlow() {
    const oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

    if (oWndInfo != null) {
      WebVideoCtrl.I_PlaySlow({
        success: function () {},
        error: function (error) {},
      });
    }
  }

  recordSearch(iType, szStartTime, szEndTime) {
    if (null == this.szDeviceIdentify.value) {
      return;
    }

    if (0 == iType) {
      // 首次搜索
      g_iSearchTimes = 0;
    }

    const self = this;

    //如果是前端设备，需要将搜索时间转换为UTC时间
    WebVideoCtrl.I_RecordSearch(
      this.szDeviceIdentify.value,
      1,
      szStartTime,
      szEndTime,
      {
        // iStreamType: 1,
        iSearchPos: g_iSearchTimes,
        success: function (xmlDoc) {
          self.searchResults.value = [];

          let responseStatusStrg =
            xmlDoc.querySelector("responseStatusStrg").textContent;

          if (responseStatusStrg === "MORE") {
            const searchMatchItems = xmlDoc.querySelectorAll("searchMatchItem");

            searchMatchItems.forEach((item, index) => {
              const playbackURI = item.querySelector("playbackURI").textContent;

              if (!playbackURI.includes("name=")) {
                return;
              }

              const startTime = item
                .querySelector("startTime")
                .textContent.replace("T", " ")
                .replace("Z", "");

              const endTime = item
                .querySelector("endTime")
                .textContent.replace("T", " ")
                .replace("Z", "");

              const fileName = playbackURI.substring(
                playbackURI.indexOf("name=") + 5,
                playbackURI.indexOf("&size=")
              );

              self.searchResults.value.push({
                id: g_iSearchTimes + index,
                fileName,
                startTime,
                endTime,
                playbackURI,
              });
            });

            g_iSearchTimes += searchMatchItems.length;

            self.recordSearch(1, szStartTime, szEndTime); // 继续搜索
          } else if (responseStatusStrg == "OK") {
            const searchMatchItems = xmlDoc.querySelectorAll("searchMatchItem");

            searchMatchItems.forEach((item, index) => {
              const playbackURI = item.querySelector("playbackURI").textContent;

              if (!playbackURI.includes("name=")) {
                return;
              }

              const startTime = item
                .querySelector("startTime")
                .textContent.replace("T", " ")
                .replace("Z", "");

              const endTime = item
                .querySelector("endTime")
                .textContent.replace("T", " ")
                .replace("Z", "");

              const fileName = playbackURI.substring(
                playbackURI.indexOf("name=") + 5,
                playbackURI.indexOf("&size=")
              );

              self.searchResults.value.push({
                id: g_iSearchTimes + index,
                fileName,
                startTime,
                endTime,
                playbackURI,
              });
            });

            g_iSearchTimes += searchMatchItems.length;
          }
        },
        error: function (error) {
          g_iSearchTimes = 0;
          console.log(
            `搜索录像失败，错误码：${error.errorCode},错误信息：${error.errorMsg}`
          );
        },
      }
    );
  }

  startDownloadRecord(index) {
    if (!this.szDeviceIdentify.value) {
      return null;
    }

    const searchResult = this.searchResults.value[index];
    const szPlaybackURI = searchResult.playbackURI;
    const szFileName = searchResult.fileName;

    WebVideoCtrl.I_StartDownloadRecord(
      this.szDeviceIdentify.value,
      szPlaybackURI,
      szFileName,
      {
        bDateDir: true, // 是否生成日期文件
      }
    ).then(
      (iDownloadID) => {
        this.downloadID.value = iDownloadID;

        // 模拟进度显示
        const downloadDiv = document.createElement("div");
        downloadDiv.id = "downProcess";
        downloadDiv.className = "freeze";
        document.body.appendChild(downloadDiv);

        this.downloadProcess.value = setInterval(() => {}, 1000);
      },
      (oError) => {
        WebVideoCtrl.I_GetLastError().then((iErrorValue) => {
          if (iErrorValue === 34) {
            this.log.value += `${this.szDeviceIdentify.value} 已下载！\n`;
          } else if (iErrorValue === 33) {
            this.log.value += `${this.szDeviceIdentify.value} 空间不足！\n`;
          } else {
            this.log.value += `${this.szDeviceIdentify.value} 下载失败！\n`;
          }
        });
      }
    );
  }
}

const hkVideoService = new HkVideoService();

export default hkVideoService;
